//
//  ViewController.swift
//  RX1_1Timer
//
//  Created by Pro on 2019/7/24.
//  Copyright © 2019 Pro. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift

class ViewController: UIViewController {
    
    

    @IBOutlet weak var topLab: UILabel!
    @IBOutlet weak var startBtn: UIButton!
    @IBOutlet weak var splitBtn: UIButton!
    @IBOutlet weak var stopBtn: UIButton!
    @IBOutlet weak var scView: UITableView!
    
    let disposBag = DisposeBag()
    
    var timer: Observable<Int>!
    
    let tabHeaderView = UILabel()

    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        
        tabHeaderView.backgroundColor = UIColor.init(white: 0.85, alpha: 1.0)
        
        let isRunning = Observable
            .merge([startBtn.rx.tap.map({return true}), stopBtn.rx.tap.map({return false})])
            .startWith(false)
            .share(replay: 1, scope: .whileConnected)
        
        isRunning.subscribe(onNext:{
            print($0)
        })
            .disposed(by: disposBag)
        
        
        let isNotRunning = isRunning
            .map({running -> Bool in
                print(running)
                return !running
            })
            .share(replay: 1, scope: .whileConnected)
        
        
        isRunning
            .bind(to: stopBtn.rx.isEnabled)
            .disposed(by: disposBag)
        
        isNotRunning
            .bind(to: splitBtn.rx.isHidden)
            .disposed(by: disposBag)
        
        isNotRunning
            .bind(to: startBtn.rx.isEnabled)
            .disposed(by: disposBag)
        
        timer = Observable<Int>
            .interval(0.1, scheduler: MainScheduler.instance)
            .withLatestFrom(isRunning, resultSelector: {_, running in running})
            .filter({runing in runing})
            .scan(0, accumulator: {(acc, _) in
                return acc+1
            })
            .startWith(0)
            .share(replay: 1, scope: .whileConnected)
        
        timer
            .subscribe{ (mecs) in
                print("\(mecs)00ms")
            }
            .disposed(by: disposBag)
        
        
        timer.map(stringFromTimeInterval)
            .bind(to: self.topLab.rx.text)
            .disposed(by: disposBag)
        
        
        let lapsSequence = timer
            .sample(splitBtn.rx.tap)
            .map(stringFromTimeInterval)
            .scan([String](), accumulator: { lapTimes, newTime in
                return lapTimes + [newTime]
            })
            .share(replay: 1, scope: .whileConnected)
        
        lapsSequence
            .bind(to: scView.rx.items(cellIdentifier: "Cell", cellType: UITableViewCell.self)) { (row, element, cell) in
                cell.textLabel?.text = "\(row+1)) \(element)"
            }
            .disposed(by: disposBag)
        
        
        scView
            .rx.setDelegate(self)
            .disposed(by: disposBag)
        
        
        lapsSequence.map({ laps -> String in
            return "\t\(laps.count) laps"
        })
            .startWith("\tno laps")
            .bind(to: tabHeaderView.rx.text)
            .disposed(by: disposBag)
        
        
        
    }
}




extension ViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return tabHeaderView
    }
}

func stringFromTimeInterval(_ ms: NSInteger) -> String {
    return String(format: "%0.2d:%0.2d.%0.1d",
                  arguments: [(ms / 600) % 600, (ms % 600 ) / 10, ms % 10])
}
